#include "Sock.hpp"
#include "Protocol.hpp"
#include <map>
#include <functional>
void *HandlerRequest(void *args)
{
    pthread_detach(pthread_self());
    int sock = *(int *)args;
    delete (int *)args;

    // version1 原生方法，没有明显的序列化和反序列化
    // 业务逻辑,做一个短服务，request->分析处理->构建response->sent(response)->close(sock)
    // 1.读取请求
    request_t req;
    char buffer[1024];
    ssize_t s = read(sock, &buffer, sizeof(buffer) - 1);
    if (s > 0)
    {
        cout << "get a new request: " << buffer << endl;
        string str = buffer;
        DeserializeRquest(str, req); // 反序列化

        // if (s == sizeof(req))
        // {
        // 2.分析请求&& 3.计算结果

        // 4.构建响应，并进行返回
        response_t res = {0, 0};
        map<char, function<int(int, int)>> func_map = {
            {'+', [](int x, int y) -> int
             { return x + y; }},
            {'-', [](int x, int y) -> int
             { return x - y; }},
            {'*', [](int x, int y) -> int
             { return x * y; }},
            {'/', [](int x, int y) -> int
             { return x / y; }},
            {'%', [](int x, int y) -> int
             { return x % y; }}};
        if (req.op == '/' && req.y == 0) // 除0错误
        {
            res.code = -1;
        }
        else if (req.op == '%' && req.y == 0) // 模0错误
        {
            res.code = -2;
        }
        else if (func_map.find(req.op) == func_map.end()) // 代表请求方法异常
        {
            res.code = -3;
        }
        else
        {
            res.result = func_map[req.op](req.x, req.y);
        }

        cout << "request: " << req.x << req.op << req.y << endl;
        //write(sock, &res, sizeof(res));
        string send_string = SerializeResponse(res);
        write(sock, send_string.c_str(), send_string.size());
        cout << "服务结束！" << send_string << endl;
        // }
    }

    // 5.关闭连接
    close(sock);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage:\n\t"
             << "server_port." << endl;
        return 1;
    }

    int listen_sock = sock::Socket();
    sock::Bind(listen_sock, atoi(argv[1]));
    sock::Listen(listen_sock);
    while (1)
    {
        int sock = sock::Accept(listen_sock);

        if (sock >= 0)
        {
            cout << "get a new client..." << endl;
            int *pram = new int(sock);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, pram);
        }
    }
    return 0;
}